package org.hong.monkey.rpc

import org.hong.monkey.MonkeyException

/**
 */
private[monkey] trait RpcEnvFactory {

  def create(config: RpcEnvConfig): RpcEnv

}

private[monkey] trait RpcEndpoint {

  val rpcEnv: RpcEnv

  final def self: RpcEndpointRef = {
    require(rpcEnv != null, "rpcEnv has not been initialized")
    rpcEnv.endpointRef(this)
  }

  def receive: PartialFunction[Any, Unit] = {
    case _ => throw new MonkeyException(self + " does not implement 'receive'")
  }

  def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
    case _ => context.sendFailure(new MonkeyException(self + " won't reply anything"))
  }

  def onError(cause: Throwable): Unit = {
    throw cause
  }

  def onConnected(remoteAddress: RpcAddress): Unit = {
  }

  def onDisconnected(remoteAddress: RpcAddress): Unit = {
  }

  def onNetworkError(cause: Throwable, remoteAddress: RpcAddress): Unit = {
  }

  def onStart(): Unit = {
  }

  def onStop(): Unit = {
  }

  final def stop(): Unit = {
    val _self = self
    if (_self != null) {
      rpcEnv.stop(_self)
    }
  }
}

private[monkey] trait ThreadSafeRpcEndpoint extends RpcEndpoint
